
package Type_1_arr.title6_P58;


import java.util.Arrays;
import java.util.Scanner;

//58. 区间和(卡码网)
public class P58RangeNum {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("第输入为整数数组的长度n：");
        int inputArrLength = scanner.nextInt();

        int[] inputArr = new int[inputArrLength];
        int[] preSumArr = new int[inputArrLength];  //TODO 核心思想  计算前缀和

        int preSum = 0;
        for (int i = 0; i < inputArrLength; i++) {
            System.out.println("数组的第" + (i + 1) + "个元素：");
            inputArr[i] = scanner.nextInt();

            //TODO 求和
            preSum += inputArr[i];
            preSumArr[i] = preSum;
        }
        System.out.println("前缀和：" + Arrays.toString(preSumArr));

        System.out.println("接下来输入需要计算总和的区间下标：");
        while (scanner.hasNextInt()) {
            int a = scanner.nextInt();
            int b = scanner.nextInt();

            int sum;  //TODO 前缀和
            if (a == 0) {
                sum = preSumArr[b];
            } else {
                sum = preSumArr[b] - preSumArr[a - 1];
            }
            System.out.println("区间[" + a + "," + b + "]的和为：" + sum);
        }

        scanner.close();
    }
}